// ID3Tab.cpp : implementation file
//

#include "stdafx.h"
#include "moretunes.h"
#include "ID3Tab.h"
#include ".\id3tab.h"
#include "winamp5.h"
#include "winmedia.h"
#include "misc.h"
#include "shareware.h"

#define MESSAGE_REPARATION_DONE "Tag changed"
#define MESSAGE_READ "Tag read"
#define MESSAGE_RENAMING_DONE "File renamed"
#define MESSAGE_RENAMING_ERROR "The file can't be renamed"
#define MESSAGE_REPARATION_ERROR "The file can't be repaired"
#define MESSAGE_NOTMP3_ERROR "Only mp3 files can be repaired"
#define URL_MORETUNES_SITE "http://code.google.com/p/moretunes/"

// CID3Tab dialog

IMPLEMENT_DYNAMIC(CID3Tab, CResizablePage)
CID3Tab::CID3Tab(CPrefTab *prefs)
	: CResizablePage(CID3Tab::IDD)
	, _fileName(_T(""))
	, _prefs(prefs)
	, _player(NULL)
	, _currentAlbum(NULL)
	, _albumsTab(NULL)
	, _tags(&theTag)
	, _showRegistration(0)
{
}

int CID3Tab::FindPlayer(void) {
	_player = &_winamp5;
	if (_winamp5.Find() == TRUE) {
		return TRUE;
	}
	if (_winMedia.Find() == TRUE) {
		_player = &_winMedia;
		return TRUE;
	}
	else if (_iTunes.Find() == TRUE) {
		_player = &_iTunes;
		return TRUE;
	}
	else {
		_winMedia.Stop();
		return FALSE;
	}
}

////////////////////////////////////////////////////////////////////////////
// The Buttons
////////////////////////////////////////////////////////////////////////////

void CID3Tab::OnBnClickedPrevious() {
	_player->Previous();
}

void CID3Tab::OnBnClickedNext() {
	_player->Next();
}

#define MESSAGE_ALLPLAYLIST "Once the process is started it cannot be stopped. \n\
Do you want to continue?"
#define MESSAGE_ALLPLAYLIST_REPAIR "Once the process is started it cannot be stopped. \n\
Artists you haven't searched with moreTunes won't be repaired. \n\
Do you want to continue?"

void CID3Tab::OnBnClickedRRAll() {
	CMenu menu;
	menu.CreatePopupMenu();
	menu.AppendMenu(MF_POPUP | MF_STRING, ID_RENAME, (LPCTSTR)"Rename all tracks of the playlist");	
	menu.AppendMenu(MF_POPUP | MF_STRING, ID_REPAIR, (LPCTSTR)"Repair all tracks of the playlist");
//	menu.AppendMenu(MF_POPUP | MF_STRING, ID_RENAME_REPAIR, (LPCTSTR)"Repair && rename the playlist");
	POINT pt;
	::GetCursorPos(&pt);
	menu.TrackPopupMenu(TPM_CENTERALIGN, pt.x, pt.y, this);
}

#define SHOW_REGISTRATION_EVERY 2
void CID3Tab::OnBnClickedRename() {
	if (_prefs->_registration != REGISTRATION_OK 
		&& (++_showRegistration % SHOW_REGISTRATION_EVERY) == 0) {
		CShareware shareware;
		shareware.DoModal();
	}
	if (renameSong() == NULL)
		_operationStatus.SetWindowText(MESSAGE_RENAMING_ERROR);
	else {
		_operationStatus.SetWindowText(MESSAGE_RENAMING_DONE);
	}
	Invalidate();
	UpdateWindow();
}

void CID3Tab::OnBnClickedRepair()
{
	if (_prefs->_registration != REGISTRATION_OK 
		&& (++_showRegistration % SHOW_REGISTRATION_EVERY) == 0) {
		CShareware shareware;
		shareware.DoModal();
	}
	readProposal();
	int res = repairSong();
	if (res == NULL)
		_operationStatus.SetWindowText(MESSAGE_REPARATION_ERROR);
	if (res == -1)
		_operationStatus.SetWindowText(MESSAGE_NOTMP3_ERROR);
	else {
		_operationStatus.SetWindowText(MESSAGE_REPARATION_DONE);
		if (_albumsTab->_searching == FALSE)
			_albumsTab->setSearchReady(_albumsTab->_searchResult); // to reload proposal
	}
	Invalidate();
	UpdateWindow();
}

////////////////////////////////////////////////////////////////////////////
// Important
////////////////////////////////////////////////////////////////////////////


int CID3Tab::setResult(Album* currentAlbum)
{
	//read the file name for the player	
	CString fileName = "";
	if (FindPlayer())
		fileName = _player->GetFileName(_player->PlGetPos());
	if (fileName == _fileName)
		return 0;
	readTag(fileName);
	setProposal(currentAlbum);
	return 1;
}

int CID3Tab::readTag(CString fileName)
{
	_fileName = "";
	theTag.Clear();

	// Test if the file exists
	CFileFind file;
	if (file.FindFile(fileName)) {
		file.Close();
		theTag.Link(fileName);
		_fileName = fileName;	
	}
	_tags.getTags(_fileName);
	return 0;
}

int CID3Tab::setProposal(Album* currentAlbum) {
	_currentAlbum = currentAlbum;
	clearProposal();

	if (_fileName.IsEmpty())
		return 0;

	// Info we can take form the current album (server info)
	if (_currentAlbum != NULL) {
		if (_currentAlbum->_matchTrack != -1)
			_trackNumData.Format("%d", _currentAlbum->_matchTrack + 1);
		else
			_trackNumData = "";
		if (_currentAlbum->_matchTrack != -1)
			_titleData = _currentAlbum->getTracks(_currentAlbum->_matchTrack);
		else 
			_titleData = "";
		if (_currentAlbum->getArtist() != "Various Artists" 
			&& _currentAlbum->getArtist() != "Original Soundtrack")
			_artistData = _currentAlbum->getArtist();
		if (_lockFields.GetCheck() == FALSE) {
			_albumData = _currentAlbum->getTitle();
			_yearData = _currentAlbum->getDateYear();
			_genreData = _currentAlbum->getGenre();
		}
	}

	// Things that never change
	if (_lockFields.GetCheck() == FALSE)
		_commentData = "";
	if (_lockV2Fields.GetCheck() == FALSE) {
		_copyrightData = _prefs->_copyrightData;
		_urlData = "";//URL_MORETUNES_SITE;
		_encodedData = _prefs->_encoderData;
	}
	// Set the proposal according to the current ID3 Info
	if (_tags._trackNumData != "" && (_trackNumData == "" || _prefs->_existingData == 0)) // TrackNum
		_trackNumData = _tags._trackNumData;
	if (_tags._titleData != "" && (_titleData == "" || _prefs->_existingData == 0)) // Title
		_titleData = _tags._titleData;
	if (_tags._artistData != "" && (_artistData == "" || _prefs->_existingData == 0)) // Artist
		_artistData = _tags._artistData;
	if (_lockFields.GetCheck() == FALSE) {
		if (_tags._albumData != "" && (_albumData == "" || _prefs->_existingData == 0)) // Album
			_albumData = _tags._albumData;
		if (_tags._yearData != "" && (_yearData == "" || _prefs->_existingData == 0)) // Year
			_yearData = _tags._yearData;
		if (_tags._genreData != "" && (_genreData == "" || _prefs->_existingData == 0)) // Genre
			_genreData = _tags._genreData;
		if (_tags._commentData != "") // Comment
			_commentData = _tags._commentData;
	}
	if (_lockV2Fields.GetCheck() == FALSE) {
		if (_tags._copyrightData != "" && (_copyrightData == "" || _prefs->_existingData == 0)) // Copyright
			_copyrightData = _tags._copyrightData;
		if (_tags._urlData != "" && (_urlData == "" || _prefs->_existingData == 0)) // URL
			_urlData = _tags._urlData;
		if (_tags._encodedByData != "" && (_encodedData == "" || _prefs->_existingData == 0)) // Encoded By
			_encodedData = _tags._encodedByData;
	}

	// Figure out the info with the file name (last resort)
	if (_artistData.IsEmpty())
			_artistData = myPathParser(_fileName, true);
	if (_titleData.IsEmpty())
		_titleData = myPathParser(_fileName, false);
	return 1;
}

CString CID3Tab::getTitleName(void) {
	if (_fileName.IsEmpty())
		return "";
	CString temp;
	temp = _tags._titleData;
	if (temp.IsEmpty())
		temp = myPathParser(_fileName, false);
	return temp;
}

int CID3Tab::renameSong(void) {
	if (_fileName.IsEmpty()) 
		return FALSE;

	// Save the current player status
	int plPos = _player->PlGetPos();
	int pos = 0;
	int isPlaying = _player->IsPlaying();
	if (isPlaying == TRUE)
		pos = _player->GetPosition();
	_player->Stop();
	int res = TRUE;

	// Build the new name
	CString newName = _prefs->_fileNameData;
	CString id3 = "";
	if (_tags._trackNumData != "") // Track
		id3 = _tags._trackNumData;
	else
		id3 = _trackNumData;
	if (id3.GetLength() == 1 && _prefs->_numFormatData == TRUE)
		id3 = "0" + id3;
	newName.Replace("NUM", id3);

	if (_tags._titleData != "") // Title
		newName.Replace("TITLE", _tags._titleData);
	else
		newName.Replace("TITLE", _titleData);
	if (_tags._artistData != "") // Artist
		newName.Replace("ARTIST", _tags._artistData);
	else
		newName.Replace("ARTIST", _artistData);
	if (_tags._albumData != "") // Album
		newName.Replace("ALBUM", _tags._albumData);
	else
		newName.Replace("ALBUM", _albumData);
	if (_tags._yearData != "") // YEAR
		newName.Replace("YEAR", _tags._yearData);
	else
		newName.Replace("YEAR", _yearData);
	if (_tags._genreData != "") // YEAR
		newName.Replace("GENRE", _tags._genreData);
	else
		newName.Replace("GENRE", _genreData);

	newName += PathFindExtension(_fileName);

	// Change the name
	CString temp = _fileName.Left(_fileName.ReverseFind('\\') + 1);
	temp += windowsFilename(newName);
	newName = temp;
	if (_fileName != newName) {
		if (rename(_fileName, newName) == 0) {
			// Make it happen for the playlist and roll the shit
			_player->PlRemove(plPos);
			_player->PlAdd(newName.GetBuffer(), plPos);
			_player->PlSetPos(plPos);
			// Update the tags
			_fileName = newName;
			theTag.Clear();
			theTag.Link(_fileName);
			_tags.getTags(_fileName);
		}
		else {
			res = FALSE;
		}
	}
	if (isPlaying) {
		_player->Play();
		_player->SetPosition(pos);
	}
	return res;
}

int CID3Tab::repairSong(void) {
	if (_fileName.IsEmpty())
		return FALSE;
	else if (_fileName.MakeLower().Find(".mp3") == -1) 
		return -1;
	int plPos = _player->PlGetPos();
	int pos = 0;
	int isPlaying = _player->IsPlaying();
	if (isPlaying == TRUE)
		pos = _player->GetPosition();	
	_player->Stop();

	// Set the new tags
	for (int i = 0; i < 2; i++) {
		setTag(ID3FID_COMMENT, ID3FN_TEXT, _commentData);
		setTag(ID3FID_COMMENT, ID3FN_TEXT, _commentData);
		setTag(ID3FID_CONTENTTYPE, ID3FN_TEXT, _genreData);
		setTag(ID3FID_YEAR, ID3FN_TEXT, _yearData);
		setTag(ID3FID_ALBUM, ID3FN_TEXT, _albumData);
		setTag(ID3FID_LEADARTIST, ID3FN_TEXT, _artistData);
		setTag(ID3FID_TITLE, ID3FN_TEXT, _titleData);
		setTag(ID3FID_TRACKNUM, ID3FN_TEXT, _trackNumData);
		if (_prefs->_onlyV1Data == FALSE) {
			setTag(ID3FID_ENCODEDBY, ID3FN_TEXT, _encodedData);
			setTag(ID3FID_WWWUSER, ID3FN_URL, _urlData);
			setTag(ID3FID_COPYRIGHT, ID3FN_TEXT, _copyrightData);
			if (_prefs->_registration == REGISTRATION_OK && _currentAlbum != NULL)
			{
				setTag(ID3FID_PICTURE, ID3FN_DATA, _currentAlbum->getImageFile());
			}
		}
	}
	//theTag.Strip(true);
	theTag.Update(ID3TT_ID3V1);
	theTag.Update(ID3TT_ID3V2);
	_tags.getTags(_fileName);

	CString temp;
	temp = _fileName;
	temp += ".XXXXXX";

	// Test if the file exists
	CFileFind file;
	if (file.FindFile(temp)) {
		file.Close();
		remove(_fileName);
		rename(temp, _fileName);
	}

	if (plPos >= 0)
		_player->Refresh(_fileName.GetBuffer(), plPos);
	if (isPlaying) {
		_player->Play();
		_player->SetPosition(pos);
	}
	return TRUE;
}


void CID3Tab::OnPaint() {
	CPaintDC dc(this); // device context for painting
	displayCurrentInfo();
	displayProposal();
}

////////////////////////////////////////////////////////////////////////////
// Not so important
////////////////////////////////////////////////////////////////////////////

CID3Tab::~CID3Tab() {
	if (_fileName != "")
		theTag.Clear();
}

void CID3Tab::DoDataExchange(CDataExchange* pDX)
{
	CResizablePage::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_EDIT7, _operationStatus);
	DDX_Control(pDX, IDC_EDIT1, _musicFile);
	DDX_Control(pDX, IDC_EDIT2, _trackNum);
	DDX_Control(pDX, IDC_EDIT13, _newTrackNum);
	DDX_Control(pDX, IDC_EDIT4, _title);
	DDX_Control(pDX, IDC_EDIT15, _newArtist);
	DDX_Control(pDX, IDC_EDIT3, _artist);
	DDX_Control(pDX, IDC_EDIT14, _newTitle);
	DDX_Control(pDX, IDC_EDIT8, _album);
	DDX_Control(pDX, IDC_EDIT18, _newGenre);
	DDX_Control(pDX, IDC_EDIT11, _year);
	DDX_Control(pDX, IDC_EDIT21, _newURL);
	DDX_Control(pDX, IDC_EDIT5, _genre);
	DDX_Control(pDX, IDC_EDIT16, _newAlbum);
	DDX_Control(pDX, IDC_EDIT9, _comment);
	DDX_Control(pDX, IDC_EDIT19, _newComment);
	DDX_Control(pDX, IDC_EDIT10, _copyright);
	DDX_Control(pDX, IDC_EDIT20, _newCopyright);
	DDX_Control(pDX, IDC_EDIT6, _url);
	DDX_Control(pDX, IDC_EDIT17, _newYear);
	DDX_Control(pDX, IDC_EDIT12, _encodedBy);
	DDX_Control(pDX, IDC_EDIT22, _newEncodedBy);
	DDX_Control(pDX, IDC_CHECK9, _lockFields);
	DDX_Control(pDX, IDC_CHECK8, _lockV2Fields);
}


BEGIN_MESSAGE_MAP(CID3Tab, CResizablePage)
	ON_BN_CLICKED(IDC_BUTTON4, OnBnClickedPrevious)
	ON_BN_CLICKED(IDC_BUTTON5, OnBnClickedRepair)
	ON_BN_CLICKED(IDC_BUTTON3, OnBnClickedNext)
	ON_BN_CLICKED(IDC_BUTTON1, OnBnClickedRRAll)
	ON_BN_CLICKED(IDC_BUTTON2, OnBnClickedRename)
	ON_WM_PAINT()
	ON_COMMAND(ID_RENAME, OnRenameAll)
	ON_COMMAND(ID_REPAIR, OnRepairAll)
	ON_COMMAND(ID_RENAME_REPAIR, OnRepairRenameAll)
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDC_CHECK9, OnBnClickedLockFields)
END_MESSAGE_MAP()

void CID3Tab::setTag(ID3_FrameID frameID, ID3_FieldID fieldID, CString tagValue) {
	if (_fileName.IsEmpty())
		return;

	ID3_Frame* myFrame;
	ID3_Field* myField;

	if ((myFrame = theTag.Find(frameID)) == NULL) {
		ID3_Frame newFrame(frameID);
		myFrame = &newFrame;
		theTag.AddFrame(&newFrame);
	}
	if ((myField = myFrame->GetField(fieldID)) != NULL) {		
		if (frameID == ID3FID_PICTURE) {
			CFile fp;
			if (fp.Open(tagValue, CFile::modeRead)) {
				if (fp.GetLength() < BAD_PIC_SIZE)
					tagValue = "";
				fp.Close();
				if (tagValue != "" && fp.Open(_currentAlbum->getImageLargeFile(), CFile::modeRead)) {
					if (fp.GetLength() > BAD_PIC_SIZE)
						tagValue = _currentAlbum->getImageLargeFile();
					fp.Close();
				}
			}
			if (tagValue != "")
			{
				myField->FromFile(tagValue);
				myFrame->GetField(ID3FN_MIMETYPE)->Set("image/jpeg");
				myFrame->GetField(ID3FN_PICTURETYPE)->Set(03);
			}
		}
		else {
			ID3_Field* encField;
			if ((encField = myFrame->GetField(ID3FN_TEXTENC)) != NULL)
				encField->Set(ID3TE_ISO8859_1);
			myField->Set(tagValue);
		}
	}
}

int CID3Tab::displayCurrentInfo(void)
{
	if (_fileName.IsEmpty()) {
		clearID3();
		return NULL;
	}
	_musicFile.SetWindowText(_fileName);
	_trackNum.SetWindowText(_tags._trackNumData);	// Track
	_title.SetWindowText(_tags._titleData);	// Title
	_artist.SetWindowText(_tags._artistData);	// Artist
	_album.SetWindowText(_tags._albumData);	// Album
	_year.SetWindowText(_tags._yearData);	// Year
	_genre.SetWindowText(_tags._genreData); // Genre
	_comment.SetWindowText(_tags._commentData);	// Comment
	_copyright.SetWindowText(_tags._copyrightData);	// Copyright
	_url.SetWindowText(_tags._urlData); // URL
	_encodedBy.SetWindowText(_tags._encodedByData); // Encoded By
	return 1;
}

int CID3Tab::displayProposal(void)
{
	if (_fileName.IsEmpty()) {
		clearProposal();
	}
	_musicFile.SetWindowText(_fileName);
	_newTrackNum.SetWindowText(_trackNumData);	// Track
	_newTitle.SetWindowText(_titleData);	// Title
	_newArtist.SetWindowText(_artistData);	// Artist
	_newAlbum.SetWindowText(_albumData);	// Album
	_newYear.SetWindowText(_yearData);	// Year
	_newGenre.SetWindowText(_genreData);	// Genre
	_newComment.SetWindowText(_commentData);	// Comment
	_newCopyright.SetWindowText(_copyrightData);	// Copyright
	_newURL.SetWindowText(_urlData); // URL
	_newEncodedBy.SetWindowText(_encodedData); // Encoded By
	return 1;
}

int CID3Tab::clearID3(void)
{
	_musicFile.SetWindowText("");
	_trackNum.SetWindowText("");	// Track
	_title.SetWindowText("");	// Title
	_artist.SetWindowText("");	// Artist
	_album.SetWindowText("");	// Album
	_year.SetWindowText("");	// Year
	_genre.SetWindowText("");	// Genre
	_comment.SetWindowText("");	// Comment
	_copyright.SetWindowText("");	// Copyright
	_url.SetWindowText(""); // URL
	_encodedBy.SetWindowText(""); // Encoded By
	return 0;
}

int CID3Tab::clearProposal(void)
{
	readProposal(); // Why is this supposed to do?
	_trackNumData = "";	// Track
	_titleData = "";	// Title
	_artistData = ""; // Artist
	if (_lockFields.GetCheck() == FALSE) {
		_albumData = "";	// Album
		_yearData = "";	// Year
		_genreData = "";	// Genre
		_commentData = "";	// Comment
	}
	if (_lockV2Fields.GetCheck() == FALSE) {
		_copyrightData = "";	// Copyright
		_urlData = ""; // URL
		_encodedData = ""; // Encoded By
	}
	return 0;
}

int CID3Tab::readProposal(void)
{
	_newTrackNum.GetWindowText(_trackNumData);	// Track
	_newTitle.GetWindowText(_titleData);	// Title
	_newArtist.GetWindowText(_artistData);	// Artist
	_newAlbum.GetWindowText(_albumData);	// Album
	_newYear.GetWindowText(_yearData);	// Year
	_newGenre.GetWindowText(_genreData);	// Genre
	_newComment.GetWindowText(_commentData);	// Comment
	_newCopyright.GetWindowText(_copyrightData);	// Copyright
	_newURL.GetWindowText(_urlData); // URL
	_newEncodedBy.GetWindowText(_encodedData); // Encoded By	
	return 1;
}

#define MESSAGE_FINISH_DL "You have to wait the current download is over before doing this"
void CID3Tab::RepairAll(void) {
	if (_prefs->_registration != REGISTRATION_OK) {
		CShareware shareware;
		shareware.DoModal();
		return;
	}
	if (AfxMessageBox(MESSAGE_ALLPLAYLIST_REPAIR,  MB_YESNO|MB_ICONEXCLAMATION) == 7)
		return;
	if (_albumsTab->_searching == TRUE) {
		AfxMessageBox(MESSAGE_FINISH_DL,  MB_ICONEXCLAMATION);
		return;
	}


	// Prepare the place
	CString progress;
	int plPos = _player->PlGetPos();
	int size = _player->PlGetSize();
	int state = _player->IsPlaying();
	int pos = 0;
	if (state == TRUE)
		pos = _player->GetPosition();
	_player->Stop();
	int autoSearch = _prefs->_autoSearchData;
	_prefs->_autoSearchData = FALSE;

	// Test the playlist
	for (int i = 0; i < size; i++) {
		progress.Format("Repairing %d / %d", i+1, size);
		_operationStatus.SetWindowText(progress);
		UpdateWindow();
		_player->PlSetPos(i);
		// that's to update the tag infos
		setResult(NULL);
		// to get a new collection of albums and the good proposal, can be optimised
		_albumsTab->_allTabs->downloadAlbums(_artistData, FALSE, FALSE);
		// Repair the song
		repairSong();
	}
	_operationStatus.SetWindowText("Playlist repaired");

	// Back to normal
	_prefs->_autoSearchData = autoSearch;
	_player->PlSetPos(plPos);
	setResult(_currentAlbum);
	_albumsTab->triggerDownload(_artistData); 
	if (state == TRUE) {
		_player->Play();
		_player->SetPosition(pos);
	}
	Invalidate();
	UpdateWindow();
}

UINT RepairAllThread( LPVOID pParam ) {
    CID3Tab* id3Tab = (CID3Tab*)pParam;
	id3Tab->RepairAll();
	return NULL;
}

void CID3Tab::OnRepairAll(void) {
	RepairAll();
}


void CID3Tab::OnRenameAll(void) {
	if (_prefs->_registration != REGISTRATION_OK) {
		CShareware shareware;
		shareware.DoModal();
		return;
	}
	if (AfxMessageBox(MESSAGE_ALLPLAYLIST,  MB_YESNO|MB_ICONEXCLAMATION) == 7)
		return;

	// Prepare the place
	CString progress;
	int plPos = _player->PlGetPos();
	int size = _player->PlGetSize();
	int state = _player->IsPlaying();
	int pos = 0;
	if (state == TRUE)
		pos = _player->GetPosition();
	_player->Stop();
	int autoSearch = _prefs->_autoSearchData;
	_prefs->_autoSearchData = FALSE;

	// Test the playlist
	for (int i = size - 1; i >= 0; i--) {
		progress.Format("Still %d files to rename", i);
		_operationStatus.SetWindowText(progress);
		UpdateWindow();
		_player->PlSetPos(i);
		setResult(NULL); // that's to update the tag infos
		renameSong();
	}
	_operationStatus.SetWindowText("Playlist renamed");

	// Back to normal
	_prefs->_autoSearchData = autoSearch;
	_player->PlSetPos(plPos);
	setResult(_currentAlbum);
	if (state == TRUE) {
		_player->Play();
		_player->SetPosition(pos);
	}
	Invalidate();
	UpdateWindow();
}

void CID3Tab::OnRepairRenameAll(void) {
}
BOOL CID3Tab::OnInitDialog() {
	CResizablePage::OnInitDialog();
	initWMP();
	FindPlayer();
	return TRUE;  // return TRUE unless you set the focus to a control
}

void CID3Tab::OnDestroy() {
	destroyWMP();
  //  if(m_pView != NULL) { // this is causing bugs, there is a memory leak here.
		//m_pView->DestroyWindow();
  //      delete m_pView;
  //  }
	CResizablePage::OnDestroy();
}

int CID3Tab::initPointers(CAlbumsTab* albumsTab) {
	_albumsTab = albumsTab;
	return 0;
}

void CID3Tab::OnBnClickedLockFields() {
	if (_lockFields.GetCheck() == FALSE && _currentAlbum != NULL) {
		setProposal(_currentAlbum);
		Invalidate();
		UpdateWindow();
	}
}

int CID3Tab::initWMP(void)
{
    HRESULT                             hr = S_OK;
    CComPtr<IObjectWithSite>            spHostObject;
    CComPtr<IAxWinHostWindow>           spHost;
    CComObject<CRemoteHost>             *pRemoteHost;

	if (_prefs->_WMPCompatibleData == FALSE)
		return 0;

    AtlAxWinInit();
    m_pView = new CAxWindow();  
    if(!m_pView)
    {
        hr = E_OUTOFMEMORY;
    }
    if(SUCCEEDED(hr)) {
        m_pView->Create(m_hWnd, NULL, NULL, WS_CHILD | WS_DISABLED);

        if(::IsWindow(m_pView->m_hWnd))
        {
            hr = m_pView->QueryHost(IID_IObjectWithSite, (void **)&spHostObject);
			if(!spHostObject.p)
			{
				hr = E_POINTER;
			}
        }
    }

	// Create remote host which implements IServiceProvider and IWMPRemoteMediaServices
    if(SUCCEEDED(hr))
    {
        hr = CComObject<CRemoteHost>::CreateInstance(&pRemoteHost);
        if(pRemoteHost)
        {
            pRemoteHost->AddRef();
        }
		else
		{
			hr = E_POINTER;
		}
    }

    // Set site to the remote host
    if(SUCCEEDED(hr))
    {
        hr = spHostObject->SetSite((IWMPRemoteMediaServices *)pRemoteHost);
    }

    if(SUCCEEDED(hr))
    {
        hr = m_pView->QueryHost(&spHost);
		if(!spHost.p)
		{
			hr = E_NOINTERFACE;
		}
    }

    // Create WMP Control here
    if(SUCCEEDED(hr))
    {
        hr = spHost->CreateControl(CComBSTR(L"{6BF52A52-394A-11d3-B153-00C04F79FAA6}"), m_pView->m_hWnd, NULL);
    }
    if(SUCCEEDED(hr))
    {
		hr = m_pView->QueryControl(&(_winMedia.m_spPlayer));
		if(!(_winMedia.m_spPlayer).p)
		{
			hr = E_NOINTERFACE;
		}
    }
    // Release remote host object
    if(pRemoteHost)
    {
        pRemoteHost->Release();
    }
	return (int)hr;
}

int CID3Tab::destroyWMP(void)
{
	if(_winMedia.m_spPlayer) { 
        _winMedia.m_spPlayer.Release();
    }
	return 1;
}
